<script>
	import userlist from './commen/tim/user'
	import {
		mapState
	} from 'vuex';
	import { judgePermissionCamera,judgePermissionRecordAudio } from 'utils/permission.js'
	export default {
		mounted() {
			/**官网有很多关于关于sdk 其他的监听方法（比如：有新的消息，用户资料更新等等）
			 * 详情可对照： https://imsdk-1252463788.file.myqcloud.com/IM_DOC/Web/SDK.html
			 * 监听的含义：服务端发生了数据变更---前端全局可以接收到变更通知--前端就可以自动触发某个事件来更新相应数据
			 * */
			// 登录成功后会触发 SDK_READY 事件，该事件触发后，可正常使用 SDK 接口
			this.tim.on(this.$TIM.EVENT.SDK_READY, this.onReadyStateUpdate, this);
			this.tim.on(this.$TIM.EVENT.SDK_NOT_READY, this.sdkOnRead, this);
			// 收到新消息
			this.tim.on(this.$TIM.EVENT.MESSAGE_RECEIVED, this.onReceiveMessage);
			// 会话列表更新
			this.tim.on(this.$TIM.EVENT.CONVERSATION_LIST_UPDATED, event => {
				this.$store.commit("updateConversationList", event.data);
			});
			// this.customLogin()
		},
		methods: {
			customLogin() {
				if (uni.getStorageSync('token')) {
					uni.switchTab({
						url: '/pages/index/index'
					});
				}
			},
			checkIsVip() {
				return new Promise((resolve, reject) => {
					this.$utils.postrequest("/api/member/is_user_vip", '', res => {
						if (res.code == 200) {
							// console.log(res.data)
							resolve(res.data)
						} else {
							reject(res.message)
						}
					})
				})
			},
			onReadyStateUpdate({
				name
			}) {
				const isSDKReady = name === this.$TIM.EVENT.SDK_READY ? true : false;
				//自动监听并更新 sdk 的ready 状态 （未登录是 notReady  登录后是ready）
				this.$store.commit("toggleIsSDKReady", isSDKReady);
				//sdk ready 后  肯定完成了登录操作    这里可以获取用户存储在im的基础信息/离线消息/黑名单列表
				// console.log("TIM状态：" + isSDKReady);
				let loginState = this.$store.state.isLogin;
				// debugger
				if (!isSDKReady && loginState) {
					uni.navigateTo({
						url: "pages/login/login"
					})
					let userInfo = JSON.parse(uni.getStorageSync('userInfo'));
					this.getUserSig(userInfo.id);
				}
			},
			sdkOnRead() {
				// console.log('-------sdk----no');
				let loginState = this.$store.state.isLogin;
				if (loginState) {
					let userInfo = JSON.parse(uni.getStorageSync('userInfo'));
					this.getUserSig(userInfo.id);
				}
			},
			onReceiveMessage({
				data: messageList
			}) {
				// 收到语音通话请求
				if (messageList[0].payload.data === 'voiceChat') {
					uni.setStorageSync('roomid', messageList[0].payload.description);
					this.$store.commit('setVoiceChatUser', JSON.parse(messageList[0].payload.extension))
					this.$store.commit('setVoiceModalShow', true)
				}
				// 语音通话被对方拒绝
				if (messageList[0].payload.data === 'voiceChatCancel') {
					this.$store.commit('setVoiceCancel', true)
				}
				// 收到对方主动挂断电话的消息
				if (messageList[0].payload.data === 'voiceChatSelfCancel') {
					// this.$store.commit('setVoiceChatSelfCancel', true)
					uni.removeStorageSync('roomid');
					this.$store.commit('setVoiceChatUser', null)
					this.$store.commit('setVoiceModalShow', false)
				}
				// 收到视频通话请求
				if (messageList[0].payload.data === 'videoChat') {
					if (this.videoChatBusy) {
						this.$store.dispatch('sendVideoChatBusy', messageList[0].from)
						return
					}
					uni.setStorageSync('roomid', messageList[0].payload.description);
					this.$store.commit('setVideoChatUser', JSON.parse(messageList[0].payload.extension))
					this.$store.commit('setVideoModalShow', true)
				}
				// 视频通话被对方拒绝
				if (messageList[0].payload.data === 'videoChatCancel') {
					this.$store.commit('setVideoCancel', true)
				}
				// 收到对方主动挂断视频的消息
				if (messageList[0].payload.data === 'videoChatSelfCancel') {
					// console.log('挂断')
					// this.$store.commit('setVideoChatSelfCancel', true)
					uni.removeStorageSync('roomid');
					this.$store.commit('setVideoChatUser', null)
					this.$store.commit('setVideoModalShow', false)
				}
				// 收到视频占线
				if (messageList[0].payload.data === 'videoChatBusy') {
					this.$store.commit('setVideoChatIsBusy', true)
				}

				let noVoiceArr = ['voiceChat', 'voiceChatCancel', 'voiceChatSelfCancel']
				if (noVoiceArr.indexOf(messageList[0].payload.data) === -1) {
					if (messageList[0].conversationType != 'GROUP') {
						let audio = uni.createInnerAudioContext()
						audio.src = './../../static/audio/get_message.mp3'
						audio.autoplay = true
						audio.play()
						audio.onEnded(function() {
							audio.destroy()
							audio = null
						})
					}
				}
				uni.setTabBarItem({
					index: 2,
					iconPath: "/static/img/message_1_unread.png",
				})
				this.$store.commit("pushCurrentMessageList", messageList);
			},
			getUserSig(userId) {
				let that = this;
				this.$utils.postrequest('/api/timuser/index?userid=' + userId, {
					userid: userId
				}, function(res) {
					if (res.code == 200) {
						// console.log("用户ID:" + userId);
						//根据返回的userID 以及 userSig 登录tim
						let promise = that.tim.login({
							userID: userId.toString(),
							userSig: res.data
						});
						promise
							.then(resData => {
								//登录成功后 更新登录状态
								that.$store.commit('toggleIsLogin', true);
								//自己平台的用户基础信息
								//tim 返回的用户信息
								uni.setStorageSync('userTIMInfo', JSON.stringify(resData.data));
								// console.log("登录成功！！！！");
							})
							.catch(err => {
								console.warn('login error:', err); // 登录失败的相关信息
							});

					} else {
						that.$utils.showLayer(res.message);
					}
				});
			},
			//根据消息列表请求聊天对象的用户信息 并完成数据拼接

		},
		onLaunch: function() {
			// #ifdef APP-PLUS
				judgePermissionCamera()
				judgePermissionRecordAudio()
			// #endif
			
			uni.onTabBarMidButtonTap(()=> {
				let isVip = uni.getStorageSync('vipInfo')
				// if (isVip) {
					uni.navigateTo({
						url: "/pages/issue/index",
						fail: (res) => {
							// console.log(res)
						}
					})
				// } else {
				// 	uni.showModal({
				// 		content: "开通会员即可发布",
				// 		cancelText: "取消",
				// 		confirmText: "去开通",
				// 		success: res => {
				// 			if (res.confirm) {
				// 				uni.navigateTo({
				// 					url: "/pages/my/vipCenter/vipCenter"
				// 				})
				// 			}
				// 		}
				// 	})
				// }
			})
			// console.log('App Launch')
			// console.log(userlist)
		},
		onShow: function() {
			// console.log('App Show')
			let stytemInfo = uni.getSystemInfoSync()
			uni.setStorageSync('stytemInfo', stytemInfo)
		},
		onHide: function() {
			// console.log('App Hide')
		},
		computed: {
			...mapState(['videoChatBusy']),
		}
	}
</script>

<style>
	/*每个页面公共css */
	[v-cloak] {
		display: none;
	}

	.uni-tabbar .uni-tabbar__mid {
		position: absolute !important;
		bottom: 12rpx !important;
	}
</style>
